package com.fh.wanandroid.ui.navigation.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fh.wanandroid.R;
import com.fh.wanandroid.app.Constants;
import com.fh.wanandroid.base.BaseFragment;
import com.fh.wanandroid.ui.articledetail.ArticleDetailActivity;
import com.fh.wanandroid.ui.mainpager.adaper.ArticleRvAdapter;
import com.fh.wanandroid.ui.mainpager.bean.FeedArticleListData;
import com.fh.wanandroid.ui.navigation.adapter.NavigationRvAdapter;
import com.fh.wanandroid.ui.navigation.bean.NavigationData;
import com.fh.wanandroid.ui.navigation.contract.NavigationContract;
import com.fh.wanandroid.ui.navigation.presenter.NavigationPresenter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import q.rorbin.verticaltablayout.VerticalTabLayout;
import q.rorbin.verticaltablayout.adapter.TabAdapter;
import q.rorbin.verticaltablayout.widget.ITabView;
import q.rorbin.verticaltablayout.widget.TabView;

public class NavigationFragment extends BaseFragment<NavigationPresenter> implements NavigationContract.View {


    @BindView(R.id.navigation_tab_layout)
    VerticalTabLayout navigationTabLayout;
    @BindView(R.id.navigation_divider)
    View navigationDivider;
    @BindView(R.id.navigation_RecyclerView)
    RecyclerView navigationRecyclerView;
    @BindView(R.id.normal_view)
    LinearLayout normalView;

    private LinearLayoutManager mManager;
    List<NavigationData.DataBean> navigationDataList;

    NavigationRvAdapter navigationRvAdapter;


    private boolean needScroll;
    private boolean isClickTab;
    private int index;

    @Override
    public NavigationPresenter getmPresenter() {
        return new NavigationPresenter();
    }

    @Override
    public void presenterSetView() {
        if (mPresenter != null) {
            mPresenter.setView(this);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_navigation;
    }

    @Override
    public void initView() {

//        mainPagerRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
//        mainPagerRecyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));


    }

    @Override
    public void initData() {
        Log.e("NavigationFragment", "--------------------3");
//        articleList = new ArrayList<FeedArticleListData.DataBean.DatasBean>();
//        mainPagerRvAdapter = new ArticleRvAdapter(getContext(), articleList);
//        mainPagerRvAdapter.setmItemClickListener(this);
//        mainPagerRecyclerView.setAdapter(mainPagerRvAdapter);

        navigationDataList = new ArrayList<>();
        mManager = new LinearLayoutManager(getContext());
        navigationRecyclerView.setLayoutManager(mManager);
        navigationRecyclerView.setHasFixedSize(true);

        navigationRvAdapter =    new NavigationRvAdapter(getContext(),navigationDataList);
        navigationRecyclerView.setAdapter(navigationRvAdapter);

    }

    @Override
    public void loadData() {

        mPresenter.loadNavigationData();
    }


    public static NavigationFragment getInstance(boolean param1, String param2) {

        NavigationFragment fragment = new NavigationFragment();
        Bundle args = new Bundle();
        args.putBoolean(Constants.ARG_PARAM1, param1);
        args.putString(Constants.ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void getNavigation(NavigationData navigationData) {

//        this.navigationDataList = navigationData.getData();
        this.navigationDataList.addAll(navigationData.getData());
        Log.e("navigationDataList","===================navigationDataList.size():"+navigationDataList.size());
        navigationTabLayout.setTabAdapter(new TabAdapter() {
            @Override
            public int getCount() {
                return navigationDataList == null ? 0 : navigationDataList.size();
            }

            @Override
            public ITabView.TabBadge getBadge(int i) {
                return null;
            }

            @Override
            public ITabView.TabIcon getIcon(int i) {
                return null;
            }

            @Override
            public ITabView.TabTitle getTitle(int i) {
                Log.e("navigationDataList","===================navigationDataList:"+navigationDataList.get(i).getName());
                return new TabView.TabTitle.Builder()
                        .setContent(navigationDataList.get(i).getName())
                        .setTextColor(ContextCompat.getColor(getContext(), R.color.shallow_green),
                                ContextCompat.getColor(getContext(), R.color.shallow_grey))
                        .build();
            }

            @Override
            public int getBackground(int i) {
                return -1;
            }
        });

        navigationRvAdapter.notifyDataSetChanged();

        leftRightLinkage();
    }

    @Override
    public void loadDataFail(String msg) {

    }


//    public void onClick(int position) {
//
//        Intent intent = new Intent(getContext(), ArticleDetailActivity.class);
//        Bundle bundle = new Bundle();
//        bundle.putInt("id", articleList.get(position).getId());
//        bundle.putString("title", articleList.get(position).getTitle());
//        bundle.putString("link", articleList.get(position).getLink());
//        intent.putExtras(bundle);
//        startActivity(intent);
//
//    }


//    public void jumpToTheTop() {
//        if (mainPagerRecyclerView != null) {
//            mainPagerRecyclerView.smoothScrollToPosition(0);
//        }
//    }


    /**
     * Left tabLayout and right recyclerView linkage
     */
    private void leftRightLinkage() {
        navigationRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (needScroll && (newState == RecyclerView.SCROLL_STATE_IDLE)) {
                    scrollRecyclerView();
                }
                rightLinkageLeft(newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (needScroll) {
                    scrollRecyclerView();
                }
            }
        });

        navigationTabLayout.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tabView, int i) {
                isClickTab = true;
                selectTag(i);
            }

            @Override
            public void onTabReselected(TabView tabView, int i) {
            }
        });
    }


    private void scrollRecyclerView() {
        needScroll = false;
        int indexDistance = index - mManager.findFirstVisibleItemPosition();
        if (indexDistance >= 0 && indexDistance < navigationRecyclerView.getChildCount()) {
            int top = navigationRecyclerView.getChildAt(indexDistance).getTop();
            navigationRecyclerView.smoothScrollBy(0, top);
        }
    }


    /**
     * Right recyclerView linkage left tabLayout
     * SCROLL_STATE_IDLE just call once
     *
     * @param newState RecyclerView new scroll state
     */
    private void rightLinkageLeft(int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            if (isClickTab) {
                isClickTab = false;
                return;
            }
            int firstPosition = mManager.findFirstVisibleItemPosition();
            if (index != firstPosition) {
                index = firstPosition;
                setChecked(index);
            }
        }
    }

    private void selectTag(int i) {
        index = i;
        navigationRecyclerView.stopScroll();
        smoothScrollToPosition(i);
    }

    /**
     * Smooth right to select the position of the left tab
     *
     * @param position checked position
     */
    private void setChecked(int position) {
        if (isClickTab) {
            isClickTab = false;
        } else {
            if (navigationTabLayout == null) {
                return;
            }
            navigationTabLayout.setTabSelected(index);
        }
        index = position;
    }

    private void smoothScrollToPosition(int currentPosition) {
        int firstPosition = mManager.findFirstVisibleItemPosition();
        int lastPosition = mManager.findLastVisibleItemPosition();
        if (currentPosition <= firstPosition) {
            navigationRecyclerView.smoothScrollToPosition(currentPosition);
        } else if (currentPosition <= lastPosition) {
            int top = navigationRecyclerView.getChildAt(currentPosition - firstPosition).getTop();
            navigationRecyclerView.smoothScrollBy(0, top);
        } else {
            navigationRecyclerView.smoothScrollToPosition(currentPosition);
            needScroll = true;
        }
    }

}
